package portal.util.xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import portal.entidades.Compra;
import portal.entidades.MonitoreoLog;
import portal.entidades.Resultado;

import com.thoughtworks.xstream.XStream;

public class XmlUtil {

	public static String resultado2Xml(Resultado resultado) {
		ResultadoXml resultadoXml = new ResultadoXml(resultado);
		XStream xstream = new XStream();
		xstream.processAnnotations(ResultadoXml.class);
		return xstream.toXML(resultadoXml);
	}
	
	public static Resultado responseXml2Resultado(String responseXml) {
		XStream xstream = new XStream();
		xstream.processAnnotations(ResponseXml.class);
		ResponseXml data = (ResponseXml) xstream.fromXML(responseXml);
		return data.toResultado();
	}
	
	public static String monitoreoLog2Xml(MonitoreoLog log) {
		MonitoreoLogXml monitoreoLogXml = new MonitoreoLogXml(log);
		XStream xstream = new XStream();
		xstream.processAnnotations(MonitoreoLogXml.class);
		return xstream.toXML(monitoreoLogXml);
	}
	
	public static String compra2Xml(Compra compra) {
		CompraXml compraXml = new CompraXml(compra);
		XStream xstream = new XStream();
		xstream.processAnnotations(CompraXml.class);
		return xstream.toXML(compraXml);
	}

	public static String getXML(Object o) throws Exception{
		JAXBContext jc;
		try {
			jc = JAXBContext.newInstance(o.getClass());
			Marshaller m = jc.createMarshaller();
	    	m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
	    			Boolean.TRUE);
	    	StringWriter writer = new StringWriter();
	    	m.marshal(o,writer);
	    	return writer.toString();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return "";	    	
	}
	
	public static <E> E getObjectFromXml(String xml, Class<E> clase) throws Exception {
		JAXBContext jc;
		try {
			return (E) JAXBContext.newInstance(clase).createUnmarshaller().unmarshal(new StringReader(xml));
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}
}
